package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.PermissionService;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: Loser
 * @Date: Created in 2020-10-14 20:55
 * @Description: 角色管理表现层
 * @Path: com.itheima.controller.RoleManagementController
 * @Modified By:
 */
@RestController
@RequestMapping("RoleManagementController")
public class RoleManagementController {

    @Reference
    private RoleService roleService;

    @Reference
    private UserService userService;

    @Reference
    private PermissionService permissionService;

    /**
     * 分页查询数据列表
     * @param queryPageBean
     * @return
     */
    @RequestMapping("findpage")
    public Result pageFind(@RequestBody QueryPageBean queryPageBean){
        try{
            PageResult pageResult = roleService.pageQuery(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());
            return new Result(false, MessageConstant.QUERY_ROLE_SUCCESS,pageResult);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ROLE_FAIL);
        }
    }

    /**
     * 查询全部关键字
     * @return
     */
    @ResponseBody
    @RequestMapping("findAll")
    public Result findAll() {
        try {
            User user = userService.findAll();
            if (user != null) {
                return new Result(true,"查询成功", user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,"查询失败",null);
    }

    /**
     * 添加
     * @param role
     * @return
     */
    @ResponseBody
    @RequestMapping("add")
    public Result add(@RequestBody Role role) {
        try {
            permissionService.add(role);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"添加失败,请稍后尝试",null);
        }
        return new Result(true,"添加成功！",null);
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public Result delete(Integer id) {
        try {
            roleService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(false,"删除失败请稍后再试",null);
        }
        return new Result(true,"删除成功",null);
    }

    /**
     * 编辑回显
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping("findById")
    public Result findById(@RequestBody Map map) {
        Integer id = (Integer) map.get("id");
        try {
            Role role = roleService.findById(id);
            return new Result(true,"查询成功", role);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询失败",null);
        }
    }

    /**
     * 修改编辑和权限修改
     * @param role
     * @return
     */
    @ResponseBody
    @RequestMapping("update")
    public Result update(@RequestBody Role role) {
        try {
            roleService.update(role);
            // 得到当前的认证信息
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            //  生成当前的所有授权
            List<GrantedAuthority> collection = new ArrayList<>(auth.getAuthorities());
            System.out.println("所有授权:" + collection);
            collection.clear();
            System.out.println("清空授权:" + collection);
            //根据角色获取到角色的keyword
            String keyword = role.getKeyword();
            //将String转成对象
            SimpleGrantedAuthority simpleGrantedAuthority02 = new SimpleGrantedAuthority(keyword);
            //添加到集合
            collection.add(simpleGrantedAuthority02);
            //根据id获取到到全部权限名(编辑后的权限id)
            List<Integer> permissionIds = role.getPermissionIds();
            //遍历所有的对象
            for (Integer permissionId : permissionIds) {
                //获得所有的字符串
                String byIdFormName = permissionService.findByIdFormName(permissionId);
                //将字符串转成对象
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(byIdFormName);
                //添加到集合中
                collection.add(simpleGrantedAuthority);
            }
            // 生成新的认证信息
            Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), collection);
            // 重置认证信息
            SecurityContextHolder.getContext().setAuthentication(newAuth);

            System.out.println("最后collection:" + collection);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"修改失败，强稍后再试",null);
        }

        return new Result(true,"修改成功",null);
    }
}
